<?php

namespace Blockgolde\HyperfBusinessWrapper\Requests;

use Blockgolde\HyperfBusinessWrapper\PaginationParamHelper;
use Psr\Container\ContainerInterface;
use Hyperf\Validation\Request\FormRequest;

class BaseRequest extends FormRequest
{
    /**
     * 自定义消息
     *
     * @var array
     */
    protected array $messages
    = [];
    /**
     * 基础消息定义
     *
     * @var array|string[]
     */
    private array $base_messages
    = [
        'required'   => ':attribute 不能为空',
        'numeric'    => ':attribute 必须是数字',
        'alpha'      => ':attribute 只能为全字母',
        'alpha_num'  => ':attribute 只能由字母数字组成',
        'alpha_dash' => ':attribute 只能为字母、数字、中划线或下划线字符',
        'en'         => ':attribute 不能包含中文',
        'date'       => ':attribute 必须为日期格式',
        'json'       => ':attribute 必须为Json格式',
        'integer'    => ':attribute 只能为整数',
        'inside'     => ':attribute 无效的数据',
    ];

    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
    }

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [];
    }

    public function messages(): array
    {
        return array_merge(parent::messages(), $this->base_messages);
    }

    public function validationData(): array
    {
        $method = $this->getMethod();
        $validated = array_merge_recursive(
            $method === 'GET' ? $this->query() : $this->post(),
            $this->getUploadedFiles()
        );
        if ($method === 'GET') {
            return (new PaginationParamHelper())->solvePageParam($validated);
        }
        return $validated;
    }

    /**
     * 根据请求方法自动切换验证规则
     *
     * @param array $rules  设定的验证规则
     * @return array  当前请求方法所需要的验证规则
     * @throws \Exception
     */
    public function useRule(array $rules): array
    {
        $method = get_current_action()['method'];

        if ($method && array_key_exists($method, $rules)) {
            return $rules[$method];
        }

        return [];
    }
}
